package com.motion_detection.public_interface;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.jwetherell.motion_detection.detection.IMotionDetection;
import com.jwetherell.motion_detection.detection.RgbMotionDetection;

public class MotionDetection extends Thread {
	private static final String TAG = "MotionDetection";
	private Handler handler = null;
	private IMotionDetection detector = new RgbMotionDetection();
	private int[] originalImage = null;
	private int[] testImage = null;
	private boolean activeDetection = false;
	private ContextWrapper contextWrapper;
	private int imageWidth;
	private int imageHeight;
	private Bitmap bitmapImage;

	public MotionDetection(Handler callback, Context context) {
		contextWrapper = new ContextWrapper(context);
		this.handler = callback;
	}

	public boolean isRunning() {
		return activeDetection;
	}

	public void startDetection(Bitmap bitmap) {
		originalImage = new int[(bitmap.getWidth() * bitmap.getHeight())];
		bitmap.getPixels(originalImage, 0, bitmap.getWidth(), 0, 0,
				bitmap.getWidth(), bitmap.getHeight());
		imageWidth = bitmap.getWidth();
		imageHeight = bitmap.getHeight();
		activeDetection = true;
		detector.detect(originalImage, imageWidth, imageHeight);
		start();
	}

	public void stopDetection() {
		activeDetection = false;
	}

	public void putImage(Bitmap newImage) {
		if (testImage == null) {
			bitmapImage = newImage;
			testImage = new int[(newImage.getWidth() * newImage.getHeight())];
			newImage.getPixels(testImage, 0, newImage.getWidth(), 0, 0,
					newImage.getWidth(), newImage.getHeight());
		}
	}

	@Override
	public void run() {
		while (activeDetection) {
			if (testImage != null) {
				if (detector.detect(testImage, imageWidth, imageHeight)) {
					Message message = new Message();
					message.obj = Boolean.valueOf(true);
					handler.sendMessage(message);
					try {
						FileOutputStream outputStream = contextWrapper
								.openFileOutput(
										String.valueOf("Porushnyk_"
												+ System.currentTimeMillis()
												+ ".png"), Context.MODE_PRIVATE);
	
						bitmapImage.compress(Bitmap.CompressFormat.PNG, 100,
								outputStream);
						outputStream.close();
					} catch (Throwable e) {
						Log.e(TAG, e.getMessage());
						e.printStackTrace();
					}
				} else {
					Message message = new Message();
					message.obj = Boolean.valueOf(false);
					handler.sendMessage(message);
				}
				testImage = null;
				bitmapImage = null;
			}
		}
	}
}
